package com.fzs.sshd.cli.server.password;

import com.fzs.sshd.cli.server.session.SessionAttributeKey;
import com.fzs.sshd.cli.server.session.SessionManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.sshd.common.SshConstants;
import org.apache.sshd.common.session.Session;
import org.apache.sshd.server.auth.AsyncAuthException;
import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.auth.password.PasswordChangeRequiredException;
import org.apache.sshd.server.session.ServerSession;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ADBPasswordAuthenticator implements PasswordAuthenticator {
    @Override
    public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException, AsyncAuthException {
        //ip白名单
        InetSocketAddress clientAddress = (InetSocketAddress) session.getClientAddress();
        log.info("from:{}:{}", clientAddress.getHostName(), clientAddress.getPort());
        //校验当前用户session数量
        if (SessionManager.sessionCountMap.getOrDefault(username, 0) >= 3){
            try {
                session.disconnect(SshConstants.SSH2_DISCONNECT_TOO_MANY_CONNECTIONS, "too many connections");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return false;
        }
        //实现自定义密码登录
        if (username.equals(password)){
            //24小时后关闭
            setSessionExpire(session);
            return true;
        }
        return false;
    }

    private static void setSessionExpire(ServerSession session) {
        LocalDateTime expTime = LocalDateTime.now().plusDays(1);
        String expKey = expTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        List<Session> sessions = SessionManager.expSessionMap.getOrDefault(expKey, new ArrayList<>());
        session.setAttribute(SessionAttributeKey.EXPIRE_TIME, expKey);
        sessions.add(session);
        SessionManager.expSessionMap.put(expKey, sessions);
    }


}
